package com.mjk.common.ai.service;


import com.mjk.common.ai.base.ThreadContext;
import com.mjk.common.ai.cosntant.AdiConstant;
import com.mjk.common.ai.dto.AiSearchRecordResp;
import com.mjk.common.ai.dto.AiSearchResp;
import com.mjk.common.ai.dto.SearchEngineResp;
import com.mjk.common.ai.entity.AiModel;
import com.mjk.common.ai.entity.AiSearchRecord;
import com.mjk.common.ai.exception.BaseException;
import com.mjk.common.ai.util.MPPageUtil;
import com.mjk.common.core.jdbc.bean.BeePage;
import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.mjk.common.ai.enums.ErrorEnum.A_DATA_NOT_FOUND;
import static com.mjk.common.ai.util.LocalCache.MODEL_ID_TO_OBJ;


/**
 * Ai search
 */
@Slf4j
@Service
public class AiSearchRecordService {

    @Autowired
    private BeeDBService beeDBService;

    /**
     * List search records
     *
     * @param maxId   Anchor id
     * @param keyword user's question
     * @return
     */
    public AiSearchResp listByMaxId(Long maxId, String keyword) {
        BeeQueryWrapper wrapper = new BeeQueryWrapper(AiSearchRecord.class);
        wrapper.eq(AiSearchRecord::getUserId, ThreadContext.getCurrentUserId());
        wrapper.eq(AiSearchRecord::getIsDeleted, false);
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.like(AiSearchRecord::getQuestion, keyword);
        }
        AiSearchResp result = new AiSearchResp();
        if (maxId > 0) {
            wrapper.it(AiSearchRecord::getId, maxId);
        }
        wrapper.orderBy(" id ");
        wrapper.setPage(0, AdiConstant.DEFAULT_PAGE_SIZE);
        BeePage<AiSearchRecord> records = beeDBService.findManyByWrapperWithPage(wrapper);
        List<AiSearchRecordResp> list = MPPageUtil.convertToList(records.getList(), AiSearchRecordResp.class);
        list.forEach(item -> {
            if (null == item.getSearchEngineResp()) {
                SearchEngineResp searchEngineResp = new SearchEngineResp();
                searchEngineResp.setItems(new ArrayList<>());
                item.setSearchEngineResp(searchEngineResp);
            }
            AiModel aiModel = MODEL_ID_TO_OBJ.get(item.getAiModelId());
            item.setAiModelPlatform(null == aiModel ? "" : aiModel.getPlatform());
            if (CollectionUtils.isNotEmpty(records.getList())) {
                result.setMinId(records.getList().stream().map(AiSearchRecord::getId).reduce(Long::min).get());
            }
            result.setRecords(list);

        });
        return result;
    }

    public boolean softDelete(String uuid) {
        BeeQueryWrapper wrapper = new BeeQueryWrapper(AiSearchRecord.class);
        wrapper.eq(AiSearchRecord::getUuid, uuid);
        if (Boolean.TRUE.equals(ThreadContext.getCurrentUser().getIsAdmin())) {
            AiSearchRecord record = new AiSearchRecord();
            record.setIsDeleted(true);
            return beeDBService.update(wrapper) > 0;
        }
        AiSearchRecord exist = (AiSearchRecord) beeDBService.findOneByWrapper(wrapper);
        if (null == exist) {
            throw new BaseException(A_DATA_NOT_FOUND);
        }
        exist.setIsDeleted(true);
        wrapper.setInstance(exist);
        return beeDBService.update(wrapper) > 0;
    }

}
